﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Windows.Forms;


namespace CsvViewer
{
    public partial class ConditionConfigControl : UserControl
    {
        Cursor precur = Cursors.Default;
        public static List<string> Fields = new List<string>();
        public static string[] ConditionTypes = { "大于", "等于", "小于", "包含", "不包含" };
        public event EventHandler CloseButtonClicked;

        public ConditionConfigControl(FilterCondition condition)
        {
            InitializeComponent();
            FromFilterCondition(condition);
        }


        private void ConditionConfigControl_Load(object sender, EventArgs e)
        {
            foreach (Control control in this.Controls)
                control.Top = (Height - control.Height) / 2;

            if (cbColumn.Items.Count == 0)
                foreach (var field in Fields)
                    cbColumn.Items.Add(field);

            if (cbConditionType.Items.Count == 0)
                foreach (var ct in ConditionTypes)
                    cbConditionType.Items.Add(ct);

            if (cbColumn.Items.Count > 0 && cbColumn.SelectedIndex < 0)
                cbColumn.SelectedIndex = 0;

            if (cbConditionType.Items.Count > 0 && cbConditionType.SelectedIndex < 0)
                cbConditionType.SelectedIndex = 1;
        }


        private void label1_MouseEnter(object sender, EventArgs e)
        {
            precur = Cursor;
            Cursor = Cursors.Hand;
        }

        private void label1_MouseLeave(object sender, EventArgs e)
        {
            Cursor = precur;
        }

        private void label1_Click(object sender, EventArgs e)
        {
            CloseButtonClicked?.Invoke(this, EventArgs.Empty);
        }


        /// <summary>
        /// To filter condition.
        /// </summary>
        /// <returns></returns>
        public FilterCondition ToFilterCondition()
        {
            FilterCondition condition = new FilterCondition();
            condition.ColumnName = cbColumn.Text;
            condition.ConditionType = cbConditionType.Text;
            condition.TargetValue = txtValue.Text;
            return condition;
        }


        /// <summary>
        /// From filter condition.
        /// </summary>
        /// <returns></returns>
        public void FromFilterCondition(FilterCondition condition)
        {
            if (condition == null) return;
            if (cbColumn.Items.Count == 0)
                foreach (var field in Fields)
                    cbColumn.Items.Add(field);

            if (cbConditionType.Items.Count == 0)
                foreach (var ct in ConditionTypes)
                    cbConditionType.Items.Add(ct);

            cbColumn.Text = condition.ColumnName;
            cbConditionType.Text = condition.ConditionType;
            txtValue.Text = condition.TargetValue;
        }
    }
}
